package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjBrandParam;
import com.zb.mapper.ZjBrandParamMapper;
import com.zb.service.ZjBrandParamService;
import com.zb.vo.BrandParamVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 品牌参数表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-08-03
 */
@Service
public class ZjBrandParamServiceImpl extends ServiceImpl<ZjBrandParamMapper, ZjBrandParam> implements ZjBrandParamService {
    @Resource
    private ZjBrandParamMapper brandParamMapper;

    // 新增或修改品牌参数
    @Override
    @Transactional
    public void save(Long custAccId, Long brandId, List<BrandParamVo> brandParamVos) {
        if (null == brandParamVos || brandParamVos.isEmpty()) {
            return;
        }
        Assert.isTrue(
                brandParamVos.stream().map(BrandParamVo::getVal).toList().size() == brandParamVos.stream().map(BrandParamVo::getVal).collect(Collectors.toSet()).size(),
                "品牌参数名已重复！", null
        );
        List<ZjBrandParam> adds = new ArrayList<>();
        List<ZjBrandParam> updates = new ArrayList<>();
        ZjBrandParam param = null;
        for (BrandParamVo vo : brandParamVos) {
            param = new ZjBrandParam();
            param.setName(vo.getName());
            param.setVal(vo.getVal());
            if (null != vo.getId()) {
                param.setId(vo.getId());
                updates.add(param);
                continue;
            }
            param.setId(IdWorker.getId());
            param.setCustAccId(custAccId);
            param.setBrandId(brandId);
            param.setName(vo.getName());
            param.setVal(vo.getVal());
            adds.add(param);
        }
        if (!adds.isEmpty()) this.saveBatch(adds);
        if (!updates.isEmpty()) this.updateBatchById(updates);
    }

    // 根据品牌ID获取品牌参数
    @Override
    public List<ZjBrandParam> getByBrandId(Long brandId) {
        QueryWrapper<ZjBrandParam> wrapper = new QueryWrapper<>();
        wrapper.select("id", "brand_id", "name", "val");
        wrapper.eq("brand_id", brandId);
        return this.list(wrapper);
    }

    // 根据品牌ID集合批量删除品牌参数
    @Override
    public void deleteBatchByBrandIds(List<Long> brandIdList) {
        brandParamMapper.deleteBatchByBrandIds(brandIdList);
    }
}
